# coding=utf-8
'''
Author: Alvin
Date: 2021-12-03 11:30:59
LastEditors: Alvin
LastEditTime: 2021-12-27 11:58:11
Description: 
Copyright © YZZH. All rights reserved.
'''
import os
from os.path import *
import cv2
from tqdm import tqdm


def image_handle(name_start_index, startSize, totalSize, imagePath, imageOutputPath, labelOutputPath, size):
    if (not os.path.exists(imageOutputPath)):
        os.makedirs(imageOutputPath)
    if (not os.path.exists(labelOutputPath)):
        os.makedirs(labelOutputPath)
    file_paths = list(
        filter(lambda x: x.lower().endswith('.jpg'), os.listdir(imagePath)))
    file_paths = file_paths[startSize:min(
        len(file_paths), startSize + totalSize)]
    for path in tqdm(file_paths):
        result = splitext(path)
        plate = result[0]
        ext = result[1]

        img = cv2.imread(join(imagePath, path))
        img = cv2.resize(img, size)
        imagename = str(name_start_index).zfill(9) + ext
        imagefilename = join(imageOutputPath, imagename)
        cv2.imwrite(imagefilename, img)

        labelname = f"{imagename}:{plate}"

        with open(join(labelOutputPath, 'train_labels.txt'), 'a', encoding='utf-8') as f:
            f.write(labelname + '\n')
        name_start_index += 1


if __name__ == "__main__":
    # ccpd plates
    image_handle(name_start_index=8474,
                 startSize=0,
                 totalSize=4000,
                 imagePath='/Volumes/Application/CCPD2019Handle/ccpd_rotate/plates',
                 imageOutputPath='/Volumes/Application/PlateData/HyperLPR/train_7s_14/train_images',
                 labelOutputPath='/Volumes/Application/PlateData/HyperLPR/train_7s_14/train_labels',
                 size=(164, 48)
                 )

    # image_handle(0,
    #              0,
    #              2560,
    #              '/Volumes/Application/CCPD2019Handle/ccpd_weather/plates',
    #              "/Volumes/Application/PlateData/HyperLPR/train_7s_12/val_images",
    #              "/Volumes/Application/PlateData/HyperLPR/train_7s_12/val_labels",
    #              (164, 48)
    #              )
